import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态定义
  const userInfo = ref({
    isLoggedIn: false,
    nickname: '',
    avatar: './images/NY_RectangularFavicon.png',
    description: '',
    username: '',
    permissions: []
  })

  const token = ref('')

  // 计算属性
  const isLoggedIn = computed(() => userInfo.value.isLoggedIn)
  
  const hasAdminPermission = computed(() => {
    return userInfo.value.permissions && userInfo.value.permissions.some(
      perm => perm !== '学生' && perm !== '教师'
    )
  })

  const isAuthenticated = computed(() => {
    return userInfo.value.isLoggedIn && !!token.value
  })

  // Actions
  const initUserInfo = async () => {
    try {
      // 从localStorage恢复token
      const savedToken = localStorage.getItem('admin_token')
      if (savedToken) {
        token.value = savedToken

        // 验证token是否仍然有效
        try {
          const { userApi } = await import('@/utils/api')
          const result = await userApi.getPermission()

          if (result.code === 200) {
            // token有效，恢复用户信息
            const savedUserInfo = localStorage.getItem('userInfo')
            if (savedUserInfo) {
              const parsedInfo = JSON.parse(savedUserInfo)
              userInfo.value = { ...userInfo.value, ...parsedInfo }
              console.log('用户状态已恢复:', userInfo.value)
            } else {
              // 没有保存的用户信息，但token有效，获取用户信息
              const userInfoResult = await userApi.getUserInfo()
              if (userInfoResult.code === 200 && userInfoResult.data) {
                const userData = userInfoResult.data
                setUserInfo({
                  isLoggedIn: true,
                  nickname: userData.nickname || userData.username,
                  avatar: userData.avatar || './images/NY_RectangularFavicon.png',
                  description: '欢迎回来！',
                  username: userData.username,
                  permissions: userData.permissions || []
                })
                console.log('用户信息已重新获取并保存')
              }
            }
          } else {
            // token无效，清除所有数据
            console.log('Token已过期，清除用户数据')
            clearUserInfo()
          }
        } catch (error) {
          console.error('验证token有效性失败:', error)
          // 网络错误或其他问题，暂时保留本地数据，但不设置为已登录状态
          const savedUserInfo = localStorage.getItem('userInfo')
          if (savedUserInfo) {
            try {
              const parsedInfo = JSON.parse(savedUserInfo)
              // 设置为未登录状态，避免显示错误的登录状态
              userInfo.value = { ...userInfo.value, ...parsedInfo, isLoggedIn: false }
            } catch (parseError) {
              console.error('解析用户信息失败:', parseError)
              clearUserInfo()
            }
          }
        }
      } else {
        // 没有token，确保清除所有用户数据
        clearUserInfo()
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error)
      clearUserInfo()
    }
  }

  const setUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    // 持久化到localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('admin_token', newToken)
  }

  const login = async (credentials, loginApi) => {
    try {
      // 调用登录API
      const result = await loginApi(credentials)

      if (result.code === 200 && result.data) {
        const userData = result.data

        console.log('登录API返回数据:', userData)
        // 设置token (后端返回的是token字段，不是tokenValue)
        const token = userData.token
        console.log('准备保存的token:', token)
        setToken(token)

        // 设置用户信息 - 修复：实际调用setUserInfo方法
        const userInfoData = {
          isLoggedIn: true,
          nickname: userData.nickname || userData.username,
          avatar: userData.avatar || './images/NY_RectangularFavicon.png',
          description: '欢迎回来！',
          username: userData.username,
          permissions: userData.permissions || []
        }
        console.log('准备保存的用户信息:', userInfoData)
        setUserInfo(userInfoData)

        // 登录成功后处理收藏数据合并
        try {
          // 动态导入避免循环依赖
          const { useFavoritesStore } = await import('./favorites')
          const favoritesStore = useFavoritesStore()
          await favoritesStore.mergeLocalFavoritesOnLogin()
        } catch (error) {
          console.error('合并收藏数据失败:', error)
        }

        // 登录成功后同步用户信息到服务器
        try {
          const { userApi } = await import('@/utils/api')
          await userApi.syncUserInfo({
            username: userData.username,
            nickname: userData.nickname || userData.username,
            avatar: userData.avatar || './images/NY_RectangularFavicon.png',
            description: '欢迎回来！',
            permissions: userData.permissions || []
          })
          console.log('用户信息同步成功')
        } catch (error) {
          console.error('用户信息同步失败:', error)
          // 同步失败不影响登录状态
        }

        return { success: true, data: userData }
      } else {
        return { success: false, message: result.msg || '登录失败' }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请检查网络连接' }
    }
  }

  const logout = async (logoutApi) => {
    try {
      // 登出前处理收藏数据
      try {
        // 动态导入避免循环依赖
        const { useFavoritesStore } = await import('./favorites')
        const favoritesStore = useFavoritesStore()
        favoritesStore.clearUserFavoritesOnLogout()
      } catch (error) {
        console.error('清除用户收藏数据失败:', error)
      }

      // 调用登出API（如果提供）
      if (logoutApi) {
        await logoutApi()
      }
    } catch (error) {
      console.error('登出API调用失败:', error)
      // 即使API调用失败，也要清除本地数据
    } finally {
      clearUserInfo()
    }
  }

  const clearUserInfo = () => {
    userInfo.value = {
      isLoggedIn: false,
      nickname: '',
      avatar: './images/NY_RectangularFavicon.png',
      description: '',
      username: '',
      permissions: []
    }
    token.value = ''
    
    // 清除localStorage
    localStorage.removeItem('userInfo')
    localStorage.removeItem('admin_token')
    localStorage.removeItem('rememberedUser')
  }

  const hasToken = () => {
    return !!token.value || !!localStorage.getItem('admin_token')
  }

  const updateUserInfo = (updates) => {
    setUserInfo(updates)
  }

  const checkLoginStatus = async (permissionApi) => {
    try {
      if (!hasToken()) {
        // 没有token，确保用户状态为未登录
        if (userInfo.value.isLoggedIn) {
          clearUserInfo()
        }
        return false
      }

      // 验证token是否有效
      const result = await permissionApi()
      if (result.code === 200) {
        // token有效，但需要检查用户状态是否正确
        if (!userInfo.value.isLoggedIn) {
          // 如果用户状态显示未登录，但token有效，需要获取用户信息
          console.log('Token有效但用户状态未登录，尝试获取用户信息')
          try {
            const { userApi } = await import('@/utils/api')
            const userInfoResult = await userApi.getUserInfo()
            if (userInfoResult.code === 200 && userInfoResult.data) {
              const userData = userInfoResult.data
              setUserInfo({
                isLoggedIn: true,
                nickname: userData.nickname || userData.username,
                avatar: userData.avatar || './images/NY_RectangularFavicon.png',
                description: '欢迎回来！',
                username: userData.username,
                permissions: userData.permissions || []
              })
              console.log('用户信息已更新')
            }
          } catch (error) {
            console.error('获取用户信息失败:', error)
          }
        }
        return true
      } else {
        // token无效，清除用户信息
        clearUserInfo()
        return false
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
      clearUserInfo()
      return false
    }
  }

  // 初始化时自动恢复状态（异步执行，不阻塞store创建）
  initUserInfo().catch(error => {
    console.error('异步初始化用户信息失败:', error)
  })

  return {
    // 状态
    userInfo,
    token,
    
    // 计算属性
    isLoggedIn,
    hasAdminPermission,
    isAuthenticated,
    
    // Actions
    initUserInfo,
    setUserInfo,
    setToken,
    login,
    logout,
    clearUserInfo,
    hasToken,
    updateUserInfo,
    checkLoginStatus
  }
})
